package com.khalil.kkadmin.module.quicklink.service;

import com.khalil.kkadmin.common.util.JsonUtil;
import com.khalil.kkadmin.infrastructure.BaseService;
import com.khalil.kkadmin.module.quicklink.domain.QuickLink;
import com.khalil.kkadmin.module.quicklink.domain.QuickLinkGroup;
import com.khalil.kkadmin.module.quicklink.domain.QuickLinkGroupRepository;
import com.khalil.kkadmin.module.quicklink.domain.QuickLinkRepository;
import com.khalil.kkadmin.module.quicklink.vo.QuickLinkGroupVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class QuickLinkServiceImpl extends BaseService<QuickLinkRepository, QuickLink, Long> implements QuickLinkService {
    private final QuickLinkGroupRepository quickLinkGroupRepository;

    public QuickLinkServiceImpl(QuickLinkRepository repository, QuickLinkGroupRepository quickLinkGroupRepository) {
        super(repository);
        this.quickLinkGroupRepository = quickLinkGroupRepository;
    }

    @Override
    protected QuickLink str2CreateEntity(String json) {
        QuickLink quickLink = JsonUtil.parseJson2Object(json, QuickLink.class);
        quickLink.setId(null);
        return quickLink;
    }

    @Override
    protected QuickLink str2UpdateEntity(String json) {
        QuickLink updated = JsonUtil.parseJson2Object(json, QuickLink.class);
        QuickLink quickLink = repository.findById(updated.getId()).orElseThrow(() -> new RuntimeException("QuickTool not found"));
        quickLink.setName(updated.getName());
        quickLink.setIcon(updated.getIcon());
        quickLink.setUrl(updated.getUrl());
        return quickLink;
    }


    @Override
    public List<QuickLink> list(String params) {
        return List.of();
    }

    @Override
    public List<QuickLinkGroupVo> listGroupsWithLinks(String uid) {
        List<QuickLink> quickLinks = repository.findByCreatedBy(uid);
        Map<Long, List<QuickLink>> group2ToolsMap = quickLinks.stream().collect(Collectors.groupingBy(QuickLink::getGroupId));

        List<QuickLinkGroup> quickLinkGroups = quickLinkGroupRepository.findByCreatedBy(uid);
        return quickLinkGroups.stream().map(group -> {
            QuickLinkGroupVo quickLinkGroupVo = new QuickLinkGroupVo();
            quickLinkGroupVo.setId(group.getId());
            quickLinkGroupVo.setName(group.getName());
            quickLinkGroupVo.setTools(group2ToolsMap.getOrDefault(group.getId(), List.of()));
            return quickLinkGroupVo;
        }).toList();
    }

    @Transactional
    @Override
    public void deleteGroupWithLinks(Long id) {
        repository.deleteByGroupId(id);
        quickLinkGroupRepository.deleteById(id);
    }
}
